package com.cuit.mapper;

import com.cuit.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    /**
     * 按用户名查询用户
     * @param username
     * @param password
     * @return
     */
    @Select("select * from user where username = #{username} and password = #{password}")
    User findByUsername(@Param("username") String username, @Param("password") String password);

    @Select({
            "<script>",
            "select id, username, nickname, email, create_time as createTime, role, avatar from user",
            "<where>",
            "   <if test='keyword != null and keyword != \"\"'>",
            "       username LIKE CONCAT('%', #{keyword}, '%')",
            "   </if>",
            "</where>",
            "</script>"
    })
    List<User> selectByKeyword(@Param("keyword") String keyword);

    @Insert("insert into user(username , nickname , email , role , avatar) values (#{username} , #{nickname} , #{email} , #{role} , #{avatar})")
    int insert(User user);

//    @Update("        UPDATE user SET\n" +
//            "        username = #{username},\n" +
//            "        nickname = #{nickname},\n" +
//            "        email = #{email},\n" +
//            "        role = #{role},\n" +
//            "        avatar = #{avatar}\n" +
//            "        WHERE id = #{id}")
    @Update("update user set username = #{username} , nickname = #{nickname} , email = #{email} , role = #{role} , avatar = #{avatar} where id = #{id}")
    int updateById(User user);

    @Delete("delete from user where id = #{id}")
    int deleteById(Long id);

    @Update("UPDATE user SET password = #{newPassword} WHERE id = #{userId}")
    void updatePassword(@Param("userId") Long userId, @Param("newPassword") String newPassword);

    // 更新用户信息
    @Update("UPDATE user SET nickname=#{nickname}, email=#{email} WHERE id=#{id}")
    void updateUser(User user);

    // 更新头像
    @Update("UPDATE user SET avatar=#{avatarUrl} WHERE id=#{userId}")
    void updateAvatar(@Param("userId") Long userId, @Param("avatarUrl") String avatarUrl);

    @Select("SELECT * FROM user WHERE id = #{userId}")
    User selectById(Long userId);
}
